import { ApiCall } from "tsrpc";
import { ReqSendChat, ResSendChat } from "../../../shared/protocols/worldServer/chat/PtlSendChat";
import { WorldServerConn } from "../../WorldServer";
import { worldServer } from "../../../WorldServerMain";

export async function ApiSendChat(call: ApiCall<ReqSendChat, ResSendChat>) {
    const conn = call.conn as WorldServerConn;
    const subWorld = conn.currentSubWorld;
    const currentUser = conn.currentUser;

    if (!subWorld || !currentUser) {
        return undefined;
    }

    let msg = {
        time: new Date,
        channel: call.req.channel,
        content: call.req.content,
        user: currentUser
    };

    if (msg.channel) {
        worldServer.masterServerConn?.sendMsg('admin/ChatTransform', msg);
    }
    else {
        worldServer.broadcastInSubWorld(subWorld, msg);
    }

    call.succ({});
}